package com.angus.common.core.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author liyanan
 * @date 2025/08/10 15:18
 * @description
 */
@Slf4j
public class IpLocationUtils {

    /**
     * 通过IP地址获取地理位置信息
     *
     * @param ip IP地址
     * @return 地理位置信息
     */
    public static String getIpLocation(String ip) {
        if (ip == null || ip.isEmpty()) {
            return "未知";
        }

        try {
            // 使用ip-api.com免费服务查询IP属地
            URL url = new URL("http://ip-api.com/json/" + ip + "?lang=zh-CN");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 简单解析JSON响应获取城市信息
            String result = response.toString();
            if (result.contains("\"city\":\"")) {
                int start = result.indexOf("\"city\":\"") + 8;
                int end = result.indexOf("\",", start);
                return result.substring(start, end);
            }
        } catch (Exception e) {
            log.error("获取IP属地信息异常: {}", e.getMessage());
        }
        return "未知";
    }
}
